<?php


namespace Beerus\Modules\SuperSubsidy\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\SuperSubsidy\YouZanBrandGoodsModel;
use Biz\model\SuperSubsidy\YouZanBrandInfoModel;
use Biz\model\SuperSubsidy\YouZanBrandItemModel;
use Biz\model\SuperSubsidy\YouZanBrandUserModel;
use Biz\model\SuperSubsidy\YouZanDeliverRecordModel;
use Biz\model\SuperSubsidy\YouZanOrders;
use Biz\service\SuperSubsidy\YouZanBrand;
use Biz\service\SuperSubsidy\YouZanDeliver;
use Biz\service\SuperSubsidy\YouZanOrder;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use PHPExcel_Cell_DataValidation;
use PhpOffice\PhpSpreadsheet\IOFactory;

class SubsidyBrandController extends Controller
{
    const PAGE_SIZE = 20;

    public function accountList(Request $request, Content $content)
    {
        $params = $request->all();
        $search_params = http_build_query($params);
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize,
        ];
        $brandName = $request->input('brand_name', null);
        $accountName = $request->input('account_name', null);
        $brandUserId = $request->input('brand_user_id', null);
        if (!empty($brandUserId)) {
            $where['id'] = $brandUserId;
        } else if (!empty($brandName)) {
            $where['brand_name[~]'] = $brandName;
        } else if (!empty($accountName)) {
            $where['account_name'] = $accountName;
        }
        $where['LIMIT'] = $limit;
        // 处理查询条件
        $list = YouZanBrandUserModel::selectByWhere($where);
        foreach ($list as $key => $item) {
            $list[$key]['account_password'] = YouZanBrand::decryptData($item['account_password']);
        }
        unset($where['LIMIT']);
        $total = YouZanBrandUserModel::count($where);
        $brandOption = YouZanBrandUserModel::selectByWhere([], ['id', 'brand_name']);
        $brandOption = array_column($brandOption, 'brand_name', 'id');
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $brandOption, $search_params) {
            $grid->tools(function ($tools) use ($search_params) {
                $tools->append('<div class="btn-group" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter" title="导出订单" href="' . url('/admin/SuperSubsidy/brand/accountList/exportBrandInfo?' . $search_params) . '" target="_blank">
<i class="fa fa-download"></i><span class="hidden-xs">导出品牌信息</span></a></div>');
            });
            $grid->paginate($gridModel->getPerPage());
            $grid->filter(function (Grid\Filter $filter) use ($brandOption) {
                $filter->disableIdFilter();
                $filter->expand();//默认展开
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($brandOption) {
                    $filter->equal('brand_user_id', '品牌账户')->select($brandOption);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('brand_name', '品牌名');
                    $filter->equal('account_name', '账户名');
                });
            });
            $grid->disableExport();
            $grid->disableBatchActions();
            $grid->column('id', '账户id');
            $grid->column('brand_name', '品牌名')->display(function () {
                $html = '<ul class="list-unstyled">';
                $html .= '<li>' . $this->brand_name . '</li>';
                $html .= '<li><a href="javascript:layer.open({
                                type: 2,
                                title: \'查看品牌信息\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'750px\', \'600px\'],
                                content: \'' . url('/admin/SuperSubsidy/brand/accountList/' . $this->id . '/brandInfo') . '\'
                            });
               ">查看品牌信息</a>';
                $html .= '</ul>';
                return $html;
            })->width(150);
            $grid->column('account_name', '账户名')->copyable();
            $grid->column('account_password', '账户密码')->copyable();
            $grid->column('created_at', '创建时间')->display(function () {
                return date('Y-m-d H:i:s', strtotime($this->update_at));
            });
            $grid->column('admin_id', '创建人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
            });
            $grid->disableActions();
        });
        $content->row($grid->render());
        return $content
            ->header("超级补贴 | 品牌账户列表")
            ->description(' ')
            ->breadcrumb(['text' => '超级补贴 | 品牌账户列表', 'url' => '/admin/SuperSubsidy/brand/accountList'], ['text' => '账户列表']);
    }

    public function brandInfo(Request $request, WorkContent $content, $id)
    {
        $brandUserInfo = YouZanBrandUserModel::getByWhere(['id' => $id]);
        $info = YouZanBrandInfoModel::getByWhere(['brand_user_id' => $id]);
        $deliver_info = $info['deliver_info'] ? json_decode($info['deliver_info'], true) : [];
        $refund_info = $info['refund_info'] ? json_decode($info['refund_info'], true) : [];
        $service_info = $info['service_info'] ? json_decode($info['service_info'], true) : [];
        $brand_info = $info['brand_info'] ? json_decode($info['brand_info'], true) : [];
        $form1 = new Form($deliver_info);
        $form1->textarea('express_company', '发货默认物流公司')->rows(4)->readonly();
        $form1->textarea('express_address', '发货地')->rows(4)->readonly();
        $form1->radio('express_calculate', '发货计费方式')->options([1 => '按件数', 2 => '按重量'])->readonly();
        $form1->textarea('express_address_fee', '发货地区邮费政策')->help('除不发货地区外，不填写的地区默认包邮')->rows(4)->readonly();
        $form1->textarea('non_express_address', '不发货地区')->rows(4)->readonly();
        $form1->textarea('delay_express_time', '可接受延期发货时间')->rows(2)->readonly();
        $form1->textarea('promise_express_time', '承诺发货时间')->rows(2)->readonly();
        $form1->disableReset();
        $form1->disableSubmit();
        $form2 = new Form($refund_info);
        $form2->textarea('refund_consignee_user', '退换货收件人')->rows(2)->readonly();
        $form2->textarea('refund_consignee_contact', '退换货联系电话')->rows(2)->readonly();
        $form2->textarea('refund_address', '退换货地址')->rows(4)->readonly();
        $form2->textarea('refund_express_fee', '退换货运费')->rows(4)->readonly();
        $form2->disableReset();
        $form2->disableSubmit();
        $form3 = new Form($service_info);
        $form3->textarea('customer_contact', '客服电话')->rows(2)->readonly();
        $form3->textarea('after_sales_contact', '售后电话')->rows(2)->readonly();
        $form3->disableReset();
        $form3->disableSubmit();
        $form4 = new Form($brand_info);
        $form4->textarea('brand_name', '品牌官方名称')->rows(2)->readonly();
        $form4->image('brand_logo', '品牌logo')->options(['showBrowse' => false])->readonly();
        $form4->disableReset();
        $form4->disableSubmit();
        $tab = new Tab();
        $tab->add('发货信息', $form1->render());
        $tab->add('退换货信息', $form2->render());
        $tab->add('售后信息', $form3->render());
        $tab->add('品牌信息', $form4->render());
        return $content
            ->header($brandUserInfo['brand_name'] . ' | ' . $info['update_at'] . ' 更新')
            ->description(' ')
            ->row($tab->render());
    }

    public function exportBrandInfo(Request $request, Content $content)
    {
        $params = $request->all();
        $accountName = $params['brand_name'] ?: '';
        $brandName = $params['account_name'] ?: '';
        $brandUserId = $params['brand_user_id'] ?: '';
        if (!empty($brandUserId)) {
            $where['id'] = $brandUserId;
        } else if (!empty($brandName)) {
            $where['brand_name[~]'] = $brandName;
        } else if (!empty($accountName)) {
            $where['account_name'] = $accountName;
        }
        $brandUserList = YouZanBrandUserModel::selectByWhere($where, ['id', 'brand_name']);
        $brandUserIds = $brandUserList ? array_column($brandUserList, 'brand_user_id') : [];
        $brandUserList = $brandUserList ? array_column($brandUserList, null, 'id') : [];
        if ($brandUserIds) {
            $where = [
                'brand_user_id' => $brandUserIds
            ];
        } else {
            $where = [];
        }
        $list = YouZanBrandInfoModel::selectByWhere($where);
        $data = [];
        foreach ($list as $info) {
            $brandUserInfo = $brandUserList[$info['brand_user_id']] ?? [];
            $deliver_info = $info['deliver_info'] ? json_decode($info['deliver_info'], true) : [];
            $refund_info = $info['refund_info'] ? json_decode($info['refund_info'], true) : [];
            $service_info = $info['service_info'] ? json_decode($info['service_info'], true) : [];
            $brand_info = $info['brand_info'] ? json_decode($info['brand_info'], true) : [];
            $express_calculate = $deliver_info['express_calculate'] ?? '';
            $express_calculate_desc = '';
            switch ($express_calculate) {
                case 1:
                    $express_calculate_desc = '按件数';
                    break;
                case 2:
                    $express_calculate_desc = '按重量';
                    break;
            }
            $data[] = [
                'brand_user_name' => $brandUserInfo['brand_name'],
                'express_company' => $deliver_info['express_company'] ?? '',
                'express_address' => $deliver_info['express_address'] ?? '',
                'express_calculate' => $express_calculate_desc,
                'express_address_fee' => $deliver_info['express_address_fee'] ?? '',
                'non_express_address' => $deliver_info['non_express_address'] ?? '',
                'delay_express_time' => $deliver_info['delay_express_time'] ?? '',
                'refund_consignee_user' => $refund_info['refund_consignee_user'] ?? '',
                'refund_consignee_contact' => $refund_info['refund_consignee_contact'] ?? '',
                'refund_address' => $refund_info['refund_address'] ?? '',
                'refund_express_fee' => $refund_info['refund_express_fee'] ?? '',
                'customer_contact' => $service_info['customer_contact'] ?? '',
                'after_sales_contact' => $service_info['after_sales_contact'] ?? '',
                'brand_name' => $brand_info['brand_name'] ?? '',
                'brand_logo' => $brand_info['brand_logo'] ?? '',
                'update_at' => $info['update_at']
            ];
        }
        $sheetData = [
            ['cell_title' => '品牌账户名称', 'cell_key' => 'A', 'cell_width' => 30, 'value_key' => 'brand_user_name'],

            ['cell_title' => '发货默认物流公司', 'cell_key' => 'B', 'cell_width' => 30, 'value_key' => 'express_company'],
            ['cell_title' => '发货地', 'cell_key' => 'C', 'cell_width' => 30, 'value_key' => 'express_address'],
            ['cell_title' => '发货计费方式', 'cell_key' => 'D', 'cell_width' => 30, 'value_key' => 'express_calculate'],
            ['cell_title' => '发货地区邮费政策', 'cell_key' => 'E', 'cell_width' => 30, 'value_key' => 'express_address_fee'],
            ['cell_title' => '不发货地区', 'cell_key' => 'F', 'cell_width' => 30, 'value_key' => 'non_express_address'],
            ['cell_title' => '可接受延期发货时间', 'cell_key' => 'G', 'cell_width' => 30, 'value_key' => 'delay_express_time'],
            ['cell_title' => '承诺发货时间', 'cell_key' => 'H', 'cell_width' => 30, 'value_key' => 'promise_express_time'],

            ['cell_title' => '退换货收件人', 'cell_key' => 'I', 'cell_width' => 30, 'value_key' => 'refund_consignee_user'],
            ['cell_title' => '退换货联系电话', 'cell_key' => 'J', 'cell_width' => 30, 'value_key' => 'refund_consignee_contact'],
            ['cell_title' => '退换货地址', 'cell_key' => 'K', 'cell_width' => 30, 'value_key' => 'refund_address'],
            ['cell_title' => '退换货运费', 'cell_key' => 'L', 'cell_width' => 30, 'value_key' => 'refund_express_fee'],

            ['cell_title' => '客服电话', 'cell_key' => 'M', 'cell_width' => 30, 'value_key' => 'customer_contact'],
            ['cell_title' => '售后电话', 'cell_key' => 'N', 'cell_width' => 30, 'value_key' => 'after_sales_contact'],

            ['cell_title' => '品牌官方名称', 'cell_key' => 'O', 'cell_width' => 30, 'value_key' => 'brand_name'],
            ['cell_title' => '品牌logo', 'cell_key' => 'P', 'cell_width' => 30, 'value_key' => 'brand_logo'],

            ['cell_title' => '更新时间', 'cell_key' => 'Q', 'cell_width' => 20, 'value_key' => 'update_at'],
        ];
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
            ],
        ];
        foreach ($sheetData as $row) {
            $cellKey = $row['cell_key'] . '1';
            $sheet->setCellValue($cellKey, $row['cell_title']);
            $sheet->getStyle($cellKey)->applyFromArray($styleArray);
            $sheet->getColumnDimension($row['cell_key'])->setWidth($row['cell_width']);
        }
        $rowNum = 2; // 从第二行开始
        foreach ($data as $info) {
            foreach ($sheetData as $row) {
                $key = $row['value_key'];
                $value = isset($info[$key]) ? $info[$key] : '';
                $cellKey = $row['cell_key'] . $rowNum;
                $sheet->setCellValue($cellKey, $value);
                $sheet->getStyle($cellKey)->applyFromArray($styleArray);
                $sheet->getStyle($cellKey)->getAlignment()->setWrapText(true);
            }
            $rowNum++;
        }
        $exportName = '导出品牌信息';
        $exportName = str_replace("+", "%20", urlencode($exportName));
        $fileName = $exportName . date('YmdHis') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    public function accountCreate(Request $request, Content $content)
    {
        $info = [];
        $form = new Form($info);
        $form->text('brand_name', '品牌名称')->required()->setWidth(4, 2);
        $form->action('/admin/SuperSubsidy/brand/accountList/saveAccount');
        return $content
            ->header('超级补贴 | 品牌账户创建')
            ->description(' ')
            ->breadcrumb(
                ['text' => '超级补贴 | 品牌账户列表', 'url' => url('/admin/SuperSubsidy/brand/accountList')],
                ['text' => '添加账户']
            )
            ->row($form->render());
    }

    public function saveAccount(Request $request)
    {
        try {
            $brandName = $request->input('brand_name', '');
            $brandName = trim($brandName);
            if ($brandName) {
                $res = YouZanBrand::createUserAccount($brandName, Admin::user()->id);
                if ($res) {
                    $success = new MessageBag([
                        'title' => '创建成功'
                    ]);
                    return redirect('/admin/SuperSubsidy/brand/accountList')->with(compact('success'));
                } else {
                    throw new \Exception('创建失败');
                }
            } else {
                throw new \Exception('请输入品牌名称');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '创建失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

}